package cn.hfatec.shms.web.up.upDocument.action;

import cn.hfatec.app.AppContext;
import cn.hfatec.shms.cache.CodeInfoCache;
import cn.hfatec.shms.constants.ShmsConstant;
import cn.hfatec.shms.constants.ShmsProperties;
import cn.hfatec.shms.enums.CodeType;
import cn.hfatec.shms.exception.NotAuthException;
import cn.hfatec.shms.system.codeInfo.service.CodeInfoService;
import cn.hfatec.shms.system.user.model.User;
import cn.hfatec.shms.system.userRole.service.UserRoleService;
import com.alibaba.fastjson.JSON;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.io.*;
import java.net.URLEncoder;
import java.util.List;
import java.util.Map;
import java.util.ArrayList;
import java.util.Arrays;
import javax.annotation.Resource;


import cn.hfatec.JsonResponse;
import cn.hfatec.Page;
import cn.hfatec.Table;
import cn.hfatec.constants.SysContant;
import cn.hfatec.freemarker.FreeMarkerUtil;
import cn.hfatec.shms.web.up.upDocument.model.UpDocumentParams;
import cn.hfatec.shms.web.up.upDocument.model.UpDocument;
import cn.hfatec.shms.web.up.upDocument.service.UpDocumentService;
import cn.hfatec.shms.base.ShmsBaseAction;
import org.springframework.ui.Model;

import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;

import org.springframework.validation.BindingResult;
import org.springframework.validation.ObjectError;
import org.springframework.web.multipart.MultipartFile;


/**
 * @author hfatec codegen
 * @version 1.0
 *          <p>
 *          the JAVA code is generate by middlegen
 */
@Controller
@RequestMapping("/up/upDocument")
public class UpDocumentAction extends ShmsBaseAction {

    //服务层
    @Resource(name = "UpDocumentService")
    private UpDocumentService upDocumentService;
    //注入Dao层
    @Resource(name = "UserRoleService")
    private UserRoleService userRoleService;
    //服务层
    @Resource(name = "CodeInfoService")
    private CodeInfoService codeInfoService;

    public static String encodeFilename(HttpServletRequest request, String fileName) {
        String rtn = "";
        try {
            String userAgent = request.getHeader("USER-AGENT");
            String new_filename = URLEncoder.encode(fileName, "UTF8");
            rtn = "filename=\"" + new_filename + "\"";
            if (userAgent != null) {
                userAgent = userAgent.toLowerCase();
                if (userAgent.indexOf("msie") != -1) {
                    rtn = "filename=\"" + new_filename + "\"";
                } else if (userAgent.indexOf("opera") != -1) {
                    rtn = "filename*=UTF-8''" + new_filename;
                } else if (userAgent.indexOf("safari") != -1) {
                    rtn = "filename=\"" + new String(fileName.getBytes("UTF-8"), "ISO8859-1") + "\"";
                } else if (userAgent.indexOf("applewebkit") != -1) {
                    new_filename = new String(fileName.getBytes("UTF-8"), "ISO-8859-1");
                    rtn = "filename=\"" + new_filename + "\"";
                } else if (userAgent.indexOf("mozilla") != -1) {
                    rtn = "filename*=UTF-8''" + new_filename;
                }
            }
        } catch (UnsupportedEncodingException e) {
            try {
                rtn = new String(fileName.getBytes("UTF-8"), "iso-8859-1");
            } catch (UnsupportedEncodingException localUnsupportedEncodingException1) {
            }
        }
        return rtn;
    }

    /**
     * 查询列表
     */
    @RequestMapping("/list")
    public String list(UpDocumentParams upDocumentParams, Page page, Model model, HttpServletRequest request) throws NotAuthException {
        User user = (User) request.getSession().getAttribute(ShmsConstant.LOGIN_USER_SESSION_NAME);
        if (user == null) {
            throw new NotAuthException("用户未授权");
        }
        List userRole = userRoleService.queryUserRoleByUserId(user.getLoginName());

        String role = "";
        for (Object roleId : userRole) {//其内部实质上还是调用了迭代器遍历方式，这种循环方式还有其他限制，不建议使用。
            role += roleId.toString() + ",";
        }
        if (!role.contains("XS")) {
            upDocumentParams.setSpareC("XS");
        } else {
            upDocumentParams.setSpareC("");
        }
        Table table = upDocumentService.queryUpDocumentTable(upDocumentParams, page);
        model.addAttribute("upDocumentsTable", table);
        model.addAttribute("upDocumentParams", upDocumentParams);
        model.addAttribute("sortTypeList", CodeInfoCache.getCodeInfo(CodeType.SORT_TYPE));
        model.addAttribute("subcategoryTypeList", CodeInfoCache.getCodeInfo(CodeType.SUBCATEGORY_TYPE));
        return "/up/upDocument/list";
    }

    /**
     * 异步查询列表
     */
    @RequestMapping("/ajaxList")
    @ResponseBody
    public String ajaxList(UpDocumentParams upDocumentParams, Page page, Model model, HttpServletRequest request) {
        try {
            list(upDocumentParams, page, model, request);
            return new JsonResponse<Map>(JsonResponse.RETURN_SUCCESS, "", FreeMarkerUtil.render("/up/upDocument/table", model)).toString();
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
        }
        return JsonResponse.error;
    }

    /**
     * 查询列表
     */
    @RequestMapping("/udlist")
    public String udlist(UpDocumentParams upDocumentParams, Page page, Model model) {

        Table table = upDocumentService.queryUpDocumentTableUD(upDocumentParams, page);
        model.addAttribute("upDocumentsTable", table);
        model.addAttribute("upDocumentParams", upDocumentParams);
        model.addAttribute("sortTypeList", CodeInfoCache.getCodeInfo(CodeType.SORT_TYPE));
        model.addAttribute("subcategoryTypeList", CodeInfoCache.getCodeInfo(CodeType.SUBCATEGORY_TYPE));
        return "/up/upDocument/udlist";
    }

    /**
     * 异步查询列表
     */
    @RequestMapping("/udajaxList")
    @ResponseBody
    public String udajaxList(UpDocumentParams upDocumentParams, Page page, Model model) {
        try {
            udlist(upDocumentParams, page, model);
            return new JsonResponse<Map>(JsonResponse.RETURN_SUCCESS, "", FreeMarkerUtil.render("/up/upDocument/table", model)).toString();
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
        }
        return JsonResponse.error;
    }

    /**
     * 跳转到新增页
     */
    @RequestMapping("/goAdd")
    @ResponseBody
    public String goAdd(Model model) {
        try {
            UpDocument upDocument = new UpDocument();
            model.addAttribute("upDocument", upDocument);
            model.addAttribute("sortTypeList", CodeInfoCache.getCodeInfo(CodeType.SORT_TYPE));
            model.addAttribute("subcategoryTypeList", CodeInfoCache.getCodeInfo(CodeType.SUBCATEGORY_TYPE));
            return new JsonResponse<Map>(JsonResponse.RETURN_SUCCESS, "", FreeMarkerUtil.render("/up/upDocument/form", model)).toString();

        } catch (Exception e) {
            logger.error(e.getMessage(), e);
        }
        return JsonResponse.error;
    }

    /**
     * 跳转到编辑页
     */
    @RequestMapping("/goEdit")
    @ResponseBody
    public String goEdit(Integer id, Model model) {

        try {
            UpDocument upDocument = upDocumentService.getUpDocument(id);
            model.addAttribute("upDocument", upDocument);
            model.addAttribute("sortTypeList", CodeInfoCache.getCodeInfo(CodeType.SORT_TYPE));
            model.addAttribute("subcategoryTypeList", CodeInfoCache.getCodeInfo(CodeType.SUBCATEGORY_TYPE));
            return new JsonResponse<Map>(JsonResponse.RETURN_SUCCESS, "", FreeMarkerUtil.render("/up/upDocument/form", model)).toString();

        } catch (Exception e) {
            logger.error(e.getMessage(), e);
        }
        return JsonResponse.error;
    }

    /**
     * 根据IDs删除数据
     */
    @RequestMapping("/delete")
    @ResponseBody
    public String deleteUpDocument(String ids) {
        try {
            List<String> idList = new ArrayList<String>();
            if (ids.length() > 0) {
                idList = Arrays.asList(ids.split(","));
            }
            upDocumentService.deleteUpDocumentBatch(idList);
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("数据" + ids + "删除异常！");
            return new JsonResponse<String>(JsonResponse.RETURN_FAILURE, SysContant.DELETE_ERROR_MESSAGE).toString();
        }
        return new JsonResponse(JsonResponse.RETURN_SUCCESS, SysContant.DELETE_SUCCESS_MESSAGE).toString();
    }

    /**
     * @param file
     * @param request
     * @return
     */
    @RequestMapping("/save")
    @ResponseBody
    public String saveUpDocument(@Valid UpDocument upDocument, BindingResult result, MultipartFile file, HttpServletRequest request) {

        try {
            if (result.hasErrors()) {
                List<ObjectError> errors = result.getAllErrors();
                return new JsonResponse<String>(JsonResponse.RETURN_FAILURE, errors.get(0).getDefaultMessage()).toString();
            }

            if (file == null) {
                return new JsonResponse<String>(JsonResponse.RETURN_FAILURE, "上传文件不能为空！", "").toString();
            }
            return upDocumentService.saveDocument(upDocument, file, request);
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("数据UpDocument保存异常！");
            return new JsonResponse<String>(JsonResponse.RETURN_FAILURE, SysContant.SAVE_ERROR_MESSAGE).toString();
        }

    }

    /**
     * 文档下载
     *
     * @param request
     * @param response
     * @param fileName
     * @return
     */
    @RequestMapping("/downloadDoc")
    @ResponseBody
    public String downloadTemplate(HttpServletRequest request, HttpServletResponse response, String fileName, String clientFileName) {
        ShmsProperties shmsProperties = AppContext.getBean("shmsProperties", ShmsProperties.class);
        String realPath = shmsProperties.getUploadPath();
        String documentPath = shmsProperties.getUploadDocumentPath();
        String uploadFilePath = realPath + documentPath;
        FileInputStream fileInputStream = null;
        String msg = "";
        try {

            File file = new File(uploadFilePath + "/" + fileName);

            long fileLength = file.length();

            // 设置下载参数
            clientFileName = encodeFilename(request, clientFileName);
            response.reset();
            response.setHeader("Content-Disposition", "attachment; " + clientFileName);
            response.addHeader("Content-Length", "" + fileLength);
            response.setContentType("application/octet-stream;charset=UTF-8");
            fileInputStream = new FileInputStream(file);
            OutputStream out = response.getOutputStream();
            // 读文件
            int iBufferSize = 65000;
            byte[] buffer = new byte[65000];
            long lReadLen = 0;
            while (lReadLen < fileLength) {
                int lRead = fileInputStream.read(buffer, 0, iBufferSize);
                lReadLen += lRead;
                out.write(buffer, 0, lRead);
            }
            out.flush();
        } catch (Exception e) {
            logger.error("下载文件失败!", e);
            msg = "下载文件失败!<a href='#' onclick='javascript:history.go(-1);'>返回</a><br/>";
            msg += e.getMessage();
        } finally {
            if (fileInputStream != null) {
                try {
                    fileInputStream.close();
                } catch (IOException e) {
                }
            }
        }
        return msg;
    }

    /**
     * @param typeClass
     * @return
     */
    @RequestMapping("/getSpareB")
    @ResponseBody
    public String getSpareB(String typeClass) {
        return JSON.toJSONString(codeInfoService.getCodeInfo(CodeType.SUBCATEGORY_TYPE, typeClass));
    }
}
